/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package comunicacao;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.FacesContext;
import main.Principal;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/**
 *
 * @author Leonardo Lino
 */
public class DataWatcherRunnable implements Runnable, Watcher, AsyncCallback.StatCallback {

    ZooKeeper zk;
    Principal principal;

    public DataWatcherRunnable(ZooKeeper zk, Principal principal) {
        this.zk = zk;
        this.principal = principal;
    }

    @Override
    public void run() {

        try {
            zk.register(this);

            zk.getChildren("/AppServers", this, null);

        } catch (KeeperException ex) {
            Logger.getLogger(DataWatcherRunnable.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(DataWatcherRunnable.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    @Override
    public void process(WatchedEvent event) {
        try {
            zk.getChildren("/AppServers", this, null);
            principal.resetAppServers();
            
            
        } catch (KeeperException ex) {
            Logger.getLogger(DataWatcherRunnable.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(DataWatcherRunnable.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void processResult(int rc, String path, Object ctx, Stat stat) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}
